package tech.yunqian.slim.framework.utils;

import java.util.Arrays;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

/**
 * 获取IP方法
 * 
 * @author yq
 */
public class IpUtils {
    public static String getIpAddr(HttpServletRequest request) {
        if (request == null) {
            return "unknown";
        }
        String ipAddresses = null;
        List<String> names = Arrays.asList(
            "X-Forwarded-For",
            "Proxy-Client-IP",
            "WL-Proxy-Client-IP",
            "HTTP_CLIENT_IP",
            "X-Real-IP"
        );
        for (String name : names) {
            ipAddresses = request.getHeader(name);
            if (ipAddresses != null && ipAddresses.length() != 0 && !"unknown".equalsIgnoreCase(ipAddresses)) {
                break;
            }
        }
        String ipAddress = null;
        if (ipAddresses != null && ipAddresses.length() != 0) {
            ipAddress = ipAddresses.split(",")[0];
        }
        if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddresses)) {
            ipAddress = request.getRemoteAddr();
        }
        if (ipAddress.endsWith("0:0:0:0:0:0:1")) {
            ipAddress = "127.0.0.1";
        }
        return ipAddress;
    }
}